//
//  BFBlueToothViewController.m
//  BFoodSystem
//
//  Created by 浙江择富 on 2018/1/22.
//  Copyright © 2018年 陈名正. All rights reserved.
//
#define kHeight  50
#define kMargin  10

#import "BFBlueToothViewController.h"
#import "HHBluetoothPrinterManager.h"



@interface BFBlueToothViewController ()<UITableViewDelegate,UITableViewDataSource,HHBluetoothPrinterManagerDelegate>
{
    HHBluetoothPrinterManager *manager;
    //选中的设备
    CBPeripheral *selectedPeripheral;
  
//    NSMutableArray *sendDataArray;
  
}

@property (nonatomic,strong)UITableView *tableView;

@end

@implementation BFBlueToothViewController
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self scanStart];
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor redColor];
    [self setupTopView];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kHeight*2);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
 
    manager = [HHBluetoothPrinterManager sharedManager];
    manager.delegate = self;
     self.dataArray1 = [[NSMutableArray alloc] init];//初始化

    
}
- (void)setupTopView{
    UILabel *blueSwithLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, 0, SCREEN_WIDTH/2, kHeight)];
    [self.view addSubview:blueSwithLab];
    blueSwithLab.text = @"蓝牙开关";
    
    UISwitch *sw = [[UISwitch alloc] init];
    sw.on = YES;
    [sw addTarget:self action:@selector(swBtn:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:sw];
    
     [sw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
         make.top.equalTo(blueSwithLab.mas_top).offset(10);
         make.bottom.mas_equalTo(blueSwithLab);
        make.width.mas_equalTo(kHeight);
}];

    
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeight, SCREEN_WIDTH, 1)];
    [self.view addSubview:lineView];
    lineView.backgroundColor = [UIColor lightGrayColor];
    UILabel *blueSearchLab = [[UILabel alloc] initWithFrame:CGRectMake(kMargin, 51 ,SCREEN_WIDTH/2, kHeight)];
    [self.view addSubview:blueSearchLab];
    blueSearchLab.text = @"搜索";
    
    UIButton *scanBtn= [[UIButton alloc]init];
//    scanBtn.backgroundColor = [UIColor orangeColor];
//    [scanBtn setTitle:@"开始扫描" forState:UIControlStateNormal];
    [scanBtn setImage:[UIImage imageNamed:@"icon_search"] forState:UIControlStateNormal];
      [scanBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanStart) forControlEvents:UIControlEventTouchUpInside];
  
    [self.view addSubview:scanBtn];

    [scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.top.bottom.mas_equalTo(blueSearchLab);
        make.width.mas_equalTo(kHeight);
    }];
    
}

//switch开关事件
- (void)swBtn:(UISwitch *)swBtn{
    BOOL isSwOn = [swBtn isOn];
    if (isSwOn) {
        //蓝牙处于开启状态
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }else{
        //蓝牙关闭
   
          }
    
    
}
//开始扫描
- (void)scanStart{
    [manager scanPeripherals];
    [self.tableView reloadData];
}

- (void) didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"did Connect Peripheral");
    
    NSLog(@"ok");
}

//蓝牙代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral {//扫描到的设备
    if (peripheral.name == NULL) {

    }else{
        if (![ self.dataArray1 containsObject:peripheral]) {
               [ self.dataArray1 addObject:peripheral];
           [self.tableView reloadData];
        }
        
    }
  
}
#pragma------- tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  self.dataArray1.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    
    CBPeripheral *peripheral = [ self.dataArray1 objectAtIndex:indexPath.row];
    cell.textLabel.text = peripheral.name;
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    selectedPeripheral = [ self.dataArray1 objectAtIndex:indexPath.row];
    [manager connectPeripheral:[self.dataArray1 objectAtIndex:indexPath.row]];
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"" message:@"蓝牙已连接" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //        [UserDefults setObject:selectedPeripheral forKey:@"selectedPeripheral"];
        //        [UserDefults synchronize];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    //    }];
    [alertVc addAction:okAction];
    //    [alertVc addAction:cancelAction];
    [self presentViewController:alertVc animated:YES completion:nil];
    
}


//- (void) sendDataTimer:(NSTimer *)timer {//发送打印数据
//    //NSLog(@"send data timer");
//
//    if ([self.sendDataArray count] > 0) {
//        NSData* cmdData;
//
//        cmdData = [self.sendDataArray objectAtIndex:0];
//        [manager startPrint:cmdData];
//
//        [self.sendDataArray removeObjectAtIndex:0];
//    }
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
